package threading;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

class MyThreadPool2{
    BlockingDeque<Runnable> blockingDeque = new LinkedBlockingDeque<>();

    public void submit(Runnable task) throws InterruptedException {
         blockingDeque.put(task);
    }
    public MyThreadPool2(int corePoolSize) {
         for (int i = 0; i < corePoolSize; i++) {
             Thread t = new Thread(() -> {
                   while (true) {
                       try {
                           Runnable runnable = blockingDeque.take();
                           runnable.run();

                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       }
                   }
             });
             t.start();
         }
    }

}
class MyThreadPool3{
    //任务队列
    BlockingDeque<Runnable> queue = new LinkedBlockingDeque<>();

    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
    }


    public MyThreadPool3(int corePoolSize) {
        for (int i = 0; i < corePoolSize; i++) {
            Thread t = new Thread(() -> {
               while (true) {
                   Runnable runnable = null;
                   try {
                       runnable = queue.take();
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
                   runnable.run();
               }
            });
            t.start();
        }
    }

}
public class ThreadDemo29 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool2 pool2 = new MyThreadPool2(10);
        MyThreadPool3 pool3 = new MyThreadPool3(10);
        for (int i = 0; i < 1000; i++) {
            int number = i;
            pool3.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello " + number);
                }
            });
        }
    }
}
